﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietPublisher.BSL.BK;
using VietPublisher.Repositories.Interface;
using VietPublisher.BaseProject;
using VietPublisher.Web.Framework;
using VietPublisher.BaseProject.Models;
using VietPublisher.API.Membership;
using System.Text.RegularExpressions;
using VietPublisher.BaseProject.Models.cart;
using VietPublisher.BaseProject.Utils.Miscellaneous;
using System.Web.Security;
using System.Web.Routing;

namespace VietPublisher.Web.BK.Controllers.Customer
{
    public class HomeController : StringBaseEntityController
    {
        #region Homepage , BookView , ViewBookDescription , Category

        //
        // GET: /Home/        
        public ActionResult Index()
        {
            List<ListBook> books = RepoBook.GetBooks();
            return View(books);
        }

        public ActionResult BookView(int bookID)
        {
            ViewBook viewBook = RepoBook.GetBook(bookID);
            return View("View_Book", viewBook);
        }

        public ActionResult ViewBookDescription(int bookID)
        {
            var bookDescription = RepoBook.ViewBookDescription(bookID);

            return PartialView("_ViewBookDescription", bookDescription);
        }

        public ActionResult Category(int categoryID)
        {

            List<ListBook> books = RepoBook.GetBooksByCategoryID(categoryID);

            return View("Category", books);
        }

        #endregion

        #region Cart,UpdateQuantity,AddToCart,EmptyCart,RemoveCartItem
        [HttpGet]
        public ActionResult Cart()
        {
            Cart cart = RepoCart.GetCart();             
            return View("List_Cart", cart);
        }
        
        public ActionResult UpdateQuantity(int bookID, int quantity) {
            Cart cart = RepoCart.UpdateQuantity(bookID, quantity);
            return PartialView("_ListCart", cart);
        }

        
        public ActionResult AddToCart(int bookID, int quantity)
        {
            Cart cart = RepoCart.AddToCart(bookID, quantity);
            return Content(string.Empty);  
        //    return Redirect(Request.UrlReferrer.AbsoluteUri);
            //return RedirectToAction("Cart");
            //return View("List_Cart", cart);
        }

        public ActionResult EmptyCart()
        {
            Cart cart = RepoCart.EmptyCart();            
            return PartialView("_ListCart", cart);
           // return RedirectToAction("Cart");
            
        }   

        public ActionResult RemoveCartItem(int bookID)
        {
            Cart cart = RepoCart.RemoveCartItem(bookID);
            
          //  return RedirectToAction("Cart");
            return PartialView("_ListCart", cart);
        }

        #endregion

        #region account,LoginCustomer,LogOff,ReloadLogon

        #region membership
        /// <summary>
        /// service
        /// </summary>
        public IFormsAuthenticationService FormsService { get; set; }
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            base.Initialize(requestContext);
        }
        #endregion

        [Authorize]
        public ActionResult LogOff()
        {
            Cart cart = new Cart();
            if (Session[DConst.sessionCart] != null)
            {
                cart = (Cart)Session[DConst.sessionCart];
            }

            FormsService.SignOut();            
            Session.RemoveAll();
            Session.Clear();
          //  Session.Abandon();

            Session[DConst.sessionCart] = cart;

          //  return Redirect(Request.UrlReferrer.ToString());
            

            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// action login for user
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LoginCustomer(FormCollection collection)
        {

            

            bool result = false;
            string userName = Request.Form["userName"] != null ? Request.Form["userName"].ToString() : "";
            string passWord = Request.Form["passWord"] != null ? Request.Form["passWord"].ToString() : "";
            result = RepoAccount.LoginCustomer(userName, passWord);
            if (result)
            {
                FormsService.SignIn(userName, true);
                StoreSessionInfo();

                if (Session[DConst.sessionCart] != null)
                {
                    Cart cart = (Cart)Session[DConst.sessionCart];
                    
                }

                #region auto redirect to the page when login success
                //string returnUrl = Request.Form["returnUrl"] != null ? Request.Form["returnUrl"].ToString() : "";
                string returnUrl = "";
                try
                {
                    returnUrl = Regex.Split(Request.UrlReferrer.PathAndQuery, "ReturnUrl=")[1];
                }
                catch
                {
                }
                returnUrl = System.Web.HttpUtility.UrlDecode(returnUrl);
                if (!String.IsNullOrEmpty(returnUrl))
                {

                    return Content(returnUrl);
                }
                else
                {
                    return Content(Request.UrlReferrer.ToString());
                   // return Redirect(Request.Url.ToString());
                   // return Content("/Home/Index");
                    
                    //return RedirectToAction("Login", "Admin");
                }
                #endregion
            }
            else
            {
                FormsService.SignOut();
                return Content(result.ToString());
            }

        }//close login

        public ActionResult ReloadLogon() {
            Cart cart = Profile.GetProfile(this.UserName).cart;
            if (cart.items.Count != 0 ) {
                Session[DConst.sessionCart] = cart;
            }
            return PartialView("User_Header");
        }

        #endregion

    }//end controller
}//end namespace
